package top.fullj.sysmon;

import android.app.Application;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nonnull;

import static android.content.ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
import static android.content.ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
import static android.content.ComponentCallbacks2.TRIM_MEMORY_MODERATE;
import static android.content.ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;

/**
 * @author bruce.wu
 * @date 2025/6/26 15:06
 */
public final class SysMom {

    private static final Logger LOG = LoggerFactory.getLogger(SysMom.class);

    public static void grab(@Nonnull final Application app) {
        AppState.grab(app);
        NetworkState.grab(app);
        BatteryState.grab(app);
    }

    public static void start(@Nonnull final Application app) {
        AppState.start(app);
        NetworkState.start(app);
        BatteryState.start(app);
        Thread.setDefaultUncaughtExceptionHandler(crashHandler);
    }

    public static void stop(@Nonnull final Application app) {
        AppState.stop(app);
        NetworkState.stop(app);
        BatteryState.stop(app);
        Thread.setDefaultUncaughtExceptionHandler(crashHandler.origin);
    }

    public static void trimMemory(int level) {
        String levelName;
        switch (level) {
            case TRIM_MEMORY_COMPLETE: levelName = "COMPLETE"; break;
            case TRIM_MEMORY_MODERATE: levelName = "MODERATE"; break;
            case TRIM_MEMORY_BACKGROUND: levelName = "BACKGROUND"; break;
            case TRIM_MEMORY_UI_HIDDEN: levelName = "UI_HIDDEN"; break;
//            case TRIM_MEMORY_RUNNING_CRITICAL: levelName = "RUNNING_CRITICAL"; break;
//            case TRIM_MEMORY_RUNNING_LOW: levelName = "RUNNING_LOW"; break;
//            case TRIM_MEMORY_RUNNING_MODERATE: levelName = "RUNNING_MODERATE"; break;
            default: levelName = "UNKNOWN(" + level + ")";
        }
        LOG.info("trimMemory: " + levelName);
    }

    private SysMom() {

    }

    private static final CrashHandler crashHandler = new CrashHandler();

    static class CrashHandler implements Thread.UncaughtExceptionHandler {
        private final Thread.UncaughtExceptionHandler origin = Thread.getDefaultUncaughtExceptionHandler();
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            LOG.error("app crashed!", e);
            if (this.origin != null) {
                this.origin.uncaughtException(t, e);
            }
        }
    }

}
